/*
 * Copyright 2017-2020 Wuwei Tengyu Logistics Center Co., Ltd.
 */

package com.goblin.security;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.goblin.common.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author goblin
 * @desc: .
 * @date 2020/7/20 10:11
 */

public class RequestWrapperFilter implements Filter {

	private static Logger logger = LoggerFactory.getLogger(RequestWrapperFilter.class);

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {
		servletRequest = new RequestWrapper((HttpServletRequest) servletRequest);

		HttpServletRequest req = (HttpServletRequest) servletRequest;
		String method = req.getMethod();
		Map<String, String[]> maps = servletRequest.getParameterMap();

		logger.info("url -- {}", req.getRequestURL().toString());
		logger.info(" method -- {}", method);

		logger.info("请求参数 Query: ");
		maps.forEach((k, v) -> {
			logger.info("{} : {}", k,
					"password".equalsIgnoreCase(k) ? "******" : StrUtil.array2String(v));
		});

		String body = ((RequestWrapper) servletRequest).getBody();
		if (body.contains("password")) {
			JSONObject json = JSONObject.parseObject(body);
			if (json.containsKey("password")) {
				try {
					json.forEach((k, v) -> {
						if (k.equalsIgnoreCase("password")) {
							json.put("password", "******");
						}
					});
					body = json.toJSONString();
				}
				catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
		logger.info("请求参数 Body: {}", body);

		filterChain.doFilter(servletRequest, servletResponse);
	}

	@Override
	public void init(FilterConfig filterConfiguration) throws ServletException {
	}

	@Override
	public void destroy() {

	}
}
